window.onload = function() {
    let focus = document.querySelector('.focus');
    let ol = document.querySelector('ol');
    let ul = focus.children[0]; //轮播图外面ul 
    let w = focus.offsetWidth;
    let index = 0;
    let flag = false;
    let timer = setInterval(() => {
            index++;
            let translatex = -index * w;
            ul.style.transition = "all .5s ease";
            ul.style.transform = `translateX(${translatex}px)`;
        }, 2000)
        //过度完成的事件监听
    ul.addEventListener('transitionend', () => {
            //无缝滚动
            if (index >= 3) { //最后一张
                index = 0;
                //去掉过度效果
                ul.style.transition = "none";
                var translatex = -index * w;
                ul.style.transform = `translateX(${translatex}px)`;
            } else if (index < 0) {
                index = 2;
                ul.style.transform = `translateX(${translatex}px)`;
            }
            //小圆点变化
            ol.querySelector('.current').classList.remove('current');
            ol.children[index].classList.add('current');
        })
        //手指移动轮播图
    let startX = 0,
        moveX = 0;
    ul.addEventListener('touchstart', e => {
            startX = e.touches[0].pageX;
            clearInterval(timer);
        })
        //移动手指touchmove 计算手指移动距离
    ul.addEventListener('touchmove', e => {
            moveX = e.targetTouches[0].pageX - startX;
            let translatex = -index * w + moveX;
            ul.style.transition = "none"; //手指拖动是缓慢拖动的不需要过度
            ul.style.transform = `translateX(${translatex}px)`;
            flag = true; //只有移动了 才会进行下面的判断
            e.preventDefault(); //阻止滚动屏幕的默认行为
        })
        //手指离开，根据移动距离来判断是回弹还是播放上一张,下一张图片
    ul.addEventListener('touchend', () => {
        if (flag) { //移动过就做相应的计算
            //moveX是负数就
            if (Math.abs(moveX) > 50) { //要换照片
                //判断图片要不要动回弹
                if (moveX > 0) { //手指右滑 moveX为正
                    index--;
                } else {
                    index++;
                }
                let translatex = -index * w;
                ul.style.transition = "all .5s ease";
                ul.style.transform = `translateX(${translatex}px)`;
            } else {
                //不换图片 回弹
                let translatex = -index * w;
                ul.style.transition = "all .2s ease";
                ul.style.transform = `translateX(${translatex}px)`;
            }
        }
        //手指离开重新开启定时器 先清除定时器,保证当前页面只有一个定时器
        clearInterval(timer);
        timer = setInterval(() => {
            index++;
            let translatex = -index * w;
            ul.style.transition = "all .5s ease";
            ul.style.transform = `translateX(${translatex}px)`;
        }, 2000)

    })
}